import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { authApi } from '../../api';

// 用户信息接口
export interface UserInfo {
  id: number;
  username: string;
  email: string;
  role: string;
  permissions: string[];
}

// 菜单项接口
export interface MenuItem {
  id: number;
  path: string;
  name: string;
  icon?: string;
  component?: string;
  parent_id?: number | null;
  order_num?: number;
  hidden?: number;
  permission?: string | null;
  children?: MenuItem[];
  [key: string]: any;
}

// 认证状态接口
export interface AuthState {
  token: string | null;
  userInfo: UserInfo | null;
  isAuthenticated: boolean;
  loading: boolean;
  error: string | null;
  menus: MenuItem[];
  buttonPermissions: string[];
}

// 初始状态
const userInfoStr = localStorage.getItem('userInfo');
let userInfo = null;
try {
  if (userInfoStr && userInfoStr !== 'undefined') {
    userInfo = JSON.parse(userInfoStr);
  }
} catch (e) {
  userInfo = null;
}
const menusStr = localStorage.getItem('menus');
let menus: MenuItem[] = [];
try {
  if (menusStr && menusStr !== 'undefined') {
    menus = JSON.parse(menusStr);
  }
} catch (e) {
  menus = [];
}
const buttonPermissionsStr = localStorage.getItem('buttonPermissions');
let buttonPermissions: string[] = [];
try {
  if (buttonPermissionsStr && buttonPermissionsStr !== 'undefined') {
    buttonPermissions = JSON.parse(buttonPermissionsStr);
  }
} catch (e) {
  buttonPermissions = [];
}
const initialState: AuthState = {
  token: localStorage.getItem('token'),
  userInfo: userInfo,
  isAuthenticated: !!localStorage.getItem('token'),
  loading: false,
  error: null,
  menus,
  buttonPermissions,
};

// 异步登录action
export const loginAsync = createAsyncThunk(
  'auth/login',
  async (credentials: { username: string; password: string }) => {
    const response = await authApi.login(credentials);
    return response;
  }
);

// 异步获取用户信息action
export const getUserInfoAsync = createAsyncThunk(
  'auth/getUserInfo',
  async () => {
    const response = await authApi.getUserInfo();
    return response;
  }
);

// 认证slice
const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    // 登录
    login: (state, action: PayloadAction<{ token: string; userInfo: UserInfo; menus: MenuItem[]; buttonPermissions: string[] }>) => {
      state.token = action.payload.token;
      state.userInfo = action.payload.userInfo;
      state.isAuthenticated = true;
      state.error = null;
      state.menus = action.payload.menus;
      state.buttonPermissions = action.payload.buttonPermissions;
      // 持久化
      localStorage.setItem('token', action.payload.token);
      localStorage.setItem('userInfo', JSON.stringify(action.payload.userInfo));
      localStorage.setItem('menus', JSON.stringify(action.payload.menus));
      localStorage.setItem('buttonPermissions', JSON.stringify(action.payload.buttonPermissions));
    },
    
    // 登出
    logout: (state) => {
      state.token = null;
      state.userInfo = null;
      state.isAuthenticated = false;
      state.error = null;
      
      // 清除本地存储
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('menus');
      localStorage.removeItem('buttonPermissions');
    },
    
    // 清除错误
    clearError: (state) => {
      state.error = null;
    },
    
    // 设置加载状态
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.loading = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      // 登录异步处理
      .addCase(loginAsync.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(loginAsync.fulfilled, (state, action) => {
        state.loading = false;
        state.token = action.payload.token;
        state.userInfo = action.payload.userInfo;
        state.isAuthenticated = true;
      })
      .addCase(loginAsync.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '登录失败';
      })
      
      // 获取用户信息异步处理
      .addCase(getUserInfoAsync.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(getUserInfoAsync.fulfilled, (state, action) => {
        state.loading = false;
        state.userInfo = action.payload;
        state.isAuthenticated = true;
      })
      .addCase(getUserInfoAsync.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '获取用户信息失败';
        state.isAuthenticated = false;
      });
  },
});

export const { login, logout, clearError, setLoading } = authSlice.actions;
export default authSlice.reducer; 